import { Collection, DatasetListItem, MAX_NAME_LENGTH } from '@/common';
import datasetService from '@/api/services/datasetService';
import { useEffect, useState } from 'react';
import {
  Button,
  Dropdown,
  Empty,
  Input,
  MenuProps,
  message,
  Modal,
  Space,
  Splitter,
  Table,
  Typography,
} from 'antd';
import {
  CloseOutlined,
  DeleteOutlined,
  DownOutlined,
  EditOutlined,
  EllipsisOutlined,
  MinusCircleTwoTone,
  PlusCircleTwoTone,
  RightOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { SvgIcon } from '@/components/icon';
import dayjs from 'dayjs';
import { useUpdateEffect } from 'react-use';
import { useDebounceFn } from 'ahooks';
import useWindowWidth from '@/hooks/event/use-window-width';
import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';
import EmptyPape from '@/components/empty/EmptyPage';
import { Size } from '@/types/common';
import { Role } from '@/types/role';

const { Text } = Typography;

interface Props {
  datas: Role[];
  isAdmin: boolean;
  isPermit: boolean;
  parentSize: Size;
  onItemClicked?: (item: Role | undefined) => void;
}
const RoleParentTable = ({ datas, isAdmin, isPermit, parentSize, onItemClicked }: Props) => {
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchValue, setSearchValue] = useState('');
  const [loading, setLoading] = useState(false);
  const [renameModalVisible, setRenameModalVisible] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [selectedRows, setSelectedRows] = useState<Collection[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [newName, setNewName] = useState('');
  const [isBatchDelete, setIsBatchDelete] = useState(false);
  const [editItem, setEditItem] = useState<Collection | undefined>(undefined);
  const { isPc } = useWindowWidth();

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: Collection[]) => {
      setSelectedRows(selectedRows);
      setSelectedRowKeys(selectedRowKeys);
    },
    selectedRowKeys: selectedRowKeys,
  };
  const handleExpand = (key) => {
    console.log(`Expand row with key: ${key}`);
    // Add logic to handle expand/collapse
  };
  const columns = [
    {
      // title: <div>全部文档 ({total})</div>,
      title: <div>角色</div>,
      width: '40%',
      dataIndex: 'name',
      key: 'name',
      render: (_, record: Role) => (
        <div className="ml-2 flex items-center">
          <SvgIcon
            color="#33ADFF"
            className="mb-1 ml-1 mr-1 mt-1"
            icon="icon-park-solid--people"
            size={28}
          />
          <div className="ml-2">{record.name}</div>
        </div>
      ),
      onCell: () => ({ style: { display: 'flex' } }),
    },
    {
      title: (
        <div>
          <Input
            style={{ border: 'none', background: 'transparent', color: '#C9CEE2' }}
            placeholder="搜索..."
            className="text-sm"
            value={searchValue}
            prefix={<SearchOutlined style={{ color: '#C9CEE2', marginRight: '10px' }} />}
            onChange={(e) => {
              setSearchValue(e.target.value);
            }}
          />
        </div>
      ),
      // width: '60%',
      key: 'action',
      render: (_, record: Role) => (
        <div className="flex">
          <div className="ml-auto">
            <Space size="small">
              {/* {isPc && (
                <Text ellipsis={{ tooltip: record.updateTime }} style={{ maxWidth: '140px' }}>
                  {dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss')}
                </Text>
              )} */}
              {isAdmin && (
                <Dropdown
                  menu={{
                    items: [
                      {
                        key: '1',
                        label: '修改名称',
                        onClick: (e) => {
                          e.domEvent.stopPropagation();
                          setNewName(record.name);
                          setEditItem(record);
                          setRenameModalVisible(true);
                        },
                      },
                      {
                        key: '2',
                        label: '删除此数据接口集',
                        onClick: (e) => {
                          e.domEvent.stopPropagation();
                          setEditItem(record);
                          setDeleteModalVisible(true);
                        },
                      },
                    ],
                  }}
                  trigger={isPc ? ['hover'] : ['click']}
                  placement="bottomLeft"
                >
                  <Button
                    type="text"
                    icon={<EllipsisOutlined />}
                    onClick={(e) => {
                      e.stopPropagation();
                    }}
                  ></Button>
                </Dropdown>
              )}
            </Space>
          </div>
        </div>
      ),
      // onCell: () => ({ style: { width: '300px' } }),
    },
  ];

  const handlePageChange = (page: number, pageSize: number) => {
    setPage(page);
    setPageSize(pageSize);
  };

  const paginationConfig = {
    current: page,
    pageSize: pageSize,
    pageSizeOptions: undefined,
    total: total,
    onChange: handlePageChange,
  };

  const clearSelections = () => {
    setSelectedRows([]);
    setSelectedRowKeys([]);
  };

  const rename = async () => {
    if (!newName) {
      message.error('文档名称不能为空');
      return;
    }
    if (newName.length > MAX_NAME_LENGTH) {
      message.error(`文档名称长度不能超过 ${MAX_NAME_LENGTH} 字符`);
      return;
    }
    if (!editItem) {
      return;
    }
    await datasetService.datasetUpdate({
      id: editItem?._id,
      name: newName, // 假设 newName 是新的名称
    });
    message.success('修改名称成功！');
    setRenameModalVisible(false);
    setEditItem(undefined);
  };

  const handleDeleteConfirm = async () => {
    if (isBatchDelete) {
      const promises = selectedRows.map(async (row) => {
        await datasetService.datasetDelete(row._id);
      });

      await Promise.all(promises);
    } else {
      if (!editItem) {
        return;
      }
      await datasetService.datasetDelete(editItem._id);
    }
    message.success('删除成功！');
    setDeleteModalVisible(false);
    setEditItem(undefined);
    setIsBatchDelete(false);
    clearSelections();
  };

  const handleBatchDelete = async () => {
    setIsBatchDelete(true);
    setDeleteModalVisible(true);
  };

  const handleRowClick = (record: Role) => {
    onItemClicked && onItemClicked(record);
  };

  useEffect(() => {
    setPage(1);
    setPageSize(10);
    setTotal(0);
  }, [datas]);

  useUpdateEffect(() => {
    // setLoading(true);
  }, [page, pageSize]);

  useUpdateEffect(() => {
    // setLoading(true);
    setPage(1);
    setPageSize(10);
    // run();
  }, [searchValue]);

  return (
    <>
      <Table
        rowClassName="bg-[#F5F7FB] cursor-pointer api-table"
        className="custom-scrollbar"
        loading={loading}
        dataSource={datas.filter((item) => item.name.includes(searchValue))}
        columns={columns}
        indentSize={40}
        // rowSelection={isAdmin ? rowSelection : {}}
        rowKey={'id'}
        onRow={(record) => {
          return {
            onClick: () => handleRowClick(record), // 点击行时触发
          };
        }}
        pagination={false}
        expandable={{
          expandIcon: ({ expanded, onExpand, record }) =>
            // record.children && record.children.length > 0 ? (
            //   expanded ? (
            //     <DownOutlined onClick={(e) => onExpand(record, e)} />
            //   ) : (
            //     <RightOutlined onClick={(e) => onExpand(record, e)} />
            //   )
            // ) : null,
            null,
        }}
        locale={{
          emptyText: (
            <div style={{ textAlign: 'center', color: '#999' }}>
              <EmptyPape description="暂无数据" />
            </div>
          ),
        }}
      ></Table>

      {selectedRows.length > 0 && isAdmin && (
        <div
          className="animated-div"
          style={{
            position: 'fixed',
            bottom: '5%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: '#474C5F',
            borderRadius: '50px',
          }}
        >
          <Space className="ml-2 mr-2" style={{ height: '45px' }}>
            <Button
              style={{ color: '#fff' }}
              type="text"
              icon={<CloseOutlined />}
              onClick={clearSelections}
            ></Button>
            <span className="whitespace-nowrap text-nowrap text-xs" style={{ color: '#8E93A4' }}>
              已选 {selectedRows.length} 项
            </span>
            <Splitter />

            <Button style={{ color: '#fff' }} type="text" onClick={handleBatchDelete}>
              删除
            </Button>
          </Space>
        </div>
      )}

      <Modal
        title={<div style={{ textAlign: 'center', width: '100%' }}>重命名</div>}
        open={renameModalVisible}
        onCancel={() => {
          setRenameModalVisible(false);
        }}
        okText="确定"
        cancelText="取消"
        closable={false}
        width={300}
        centered
        footer={
          <div style={{ textAlign: 'center' }}>
            <Space size={56}>
              <Button
                onClick={() => {
                  setRenameModalVisible(false);
                }}
              >
                取消
              </Button>
              <Button type="primary" onClick={rename}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '60px',
          }}
        >
          <Input value={newName} onChange={(e) => setNewName(e.target.value)} />
        </div>
      </Modal>

      <DeleteConfirmModal
        visible={deleteModalVisible}
        text={`确定要删除吗？`}
        onCancel={() => {
          setDeleteModalVisible(false);
        }}
        onConfirm={handleDeleteConfirm}
      />
    </>
  );
};

export default RoleParentTable;
